<?php

namespace api\services\goods;

use api\extensions\ApiBaseService;
use common\models\goods\goods\GoodsDescModel;
use common\models\goods\goods\GoodsModel;
use common\services\goods\GoodsStockService;
use api\services\goods\GoodsBrandService;
use common\models\active\ActivePromotionModel;
use common\models\goods\goods\GoodsCollectModel;
use common\services\active\ActivePromotionService;
use api\services\active\ActiveCouponService;
use common\models\goods\goods\GoodsLookModel;
use common\models\goods\cate\GoodsCateModel;
/**
 * Desc 商品管理服务类
 * @author WMX
 */
class GoodsService extends ApiBaseService
{

    // 商品搜索列表
    public static function getList($params)
    {
        $where = [
            'AND',
            ['=', 'state', GoodsModel::STATE_LISTING]
        ];
        //品牌
        if ($params['brand_id']) {
            $where[] = ['IN', 'brand', $params['brand_id']];
        }
        //分类
        if ($params['cate_id']) {
            //顶级分类
            if($params['first'] == 2){
                $params['cate_id'] = array_column(GoodsCateModel::find()->where(['pid' => $params['cate_id']])->asArray()->all(), 'id');
            }
            $where[] = ['IN', 'category', $params['cate_id']];
        }
        //关键字
        if($params['keyword']){
            $where[] = ['or', ['like', 'name', $params['keyword']], ['like', 'alias', $params['keyword']]];
        }

        // 价格
        $order_by = '';
        if(isset($params['price'])){
            if($params['price'] == 1) {
                $order_by = 'sell desc';
            }
            if($params['price'] == 2) {
                $order_by = 'sell asc';
            }
        }
        // 销量
        if(isset($params['sales'])){
            if($params['sales'] == 1) {
                $order_by = strlen($order_by) > 0 ? $order_by.',sales desc' : 'sales desc';
            }
            if($params['sales'] == 2) {
                $order_by = strlen($order_by) > 0 ? $order_by.',sales asc' : 'sales asc';
            }
        }

        // 默认排序
        if(strlen($order_by) == 0) {
            $order_by = 'sales desc';
        }
        
        try {
            $goods = GoodsModel::getDataAll($where,$params['page'], 20, $order_by);
            if (empty($goods)) {
                throw new \Exception('商品为空');
            }

            // 库存
            $stock = GoodsStockService::getStock(array_column($goods['list'], 'id'));
            
            // 活动
            $activity = ActivePromotionService::getActivityInfo(array_column($goods['list'], 'id'));
            foreach ($goods['list'] as &$val) {
                $val['stock'] = isset($stock[$val['id']]) ? 1 : 2;
                $val['price'] = round($val['sell']); // 商品价格
                $val['activity_price'] = $val['price'];
                $val['act_tag'] = [];
                // 匹配商品活动信息
                if ($activity && $activity[$val['id']]) {
                    $val['act'] = $activity[$val['id']];
                    $val['act_tag'][] = $activity[$val['id']]['tag'];
                    $val['activity_price'] = ActivePromotionService::getActivityPrice($activity[$val['id']], $val['price']);
                }
                $val['sell'] = $val['activity_price'] == $val['price'] ? 0 : $val['price'];
            }
            return self::jsonSuccess($goods);
        } catch (\Exception $exc) {
            return self::jsonSuccess([
                'total'=> 0,
                'list'=> []
            ]);
        }
    }

    /**
     * 获取商品详情信息
     * * */
    public static function getDetail($id)
    {
        $user = \Yii::$app->user->getInfo();
        try {
            $data = [];
            if (empty($id)) {
                throw new \Exception('参数异常');
            }
            $goods = GoodsModel::getDataOne(['id' => $id]);
            if (empty($goods)) {
                throw new \Exception('商品信息异常');
            }
            $goods['img'] = explode(',', $goods['img']); // 商品轮播
            $goods['tag'] = explode(',', $goods['tag']); // 商品信息标签
            $goods['price'] = round($goods['sell']); // 商品价格
            $data['goods'] = $goods;

            // 获取商品活动信息
            $data['goods']['act_tag'] = []; // 商品活动标签
            $data['act'] = [];
            // $data['goods']['tag'] = [];
            $data['goods']['activity_price'] = $data['goods']['price'];
            // 获取商品活动信息
            $activity = ActivePromotionService::getActivityInfo($id);
            if ($activity && $activity[$id]) {
                $data['goods']['act_tag'][] = $activity[$id]['tag'];
                $data['act'] = [
                    'id' => $activity[$id]['id'],
                    'name' => $activity[$id]['name'],
                    'type_name' => ActivePromotionModel::$type[$activity[$id]['type']],
                    'desc' =>$activity[$id]['desc']
                ];
                $data['goods']['activity_price'] = ActivePromotionService::getActivityPrice($activity[$id], $data['goods']['price']);
            }

            $data['goods']['price'] = $data['goods']['activity_price'] == $data['goods']['price'] ? 0 : $data['goods']['price'];

            // 是否库存为0
            $data['goods']['stock'] = isset(GoodsStockService::getStock($id)[$id]) ? 1 : 2;

            //收藏——默认展示不收藏
            $data['goods']['collect'] = 1;
            if ($user) {
                $data['goods']['collect'] = GoodsCollectModel::findOne(['user_id' => $user['id'], 'gid' => $id]) ? 2 : 1;
            }

            // 品牌数据
            $data['brand'] = GoodsBrandService::getBrandGoodsTop($goods['brand']);

            // 访问足迹
            self::addHistory($id);
            return self::jsonSuccess($data);
        } catch (\Exception $exc) {
            return self::jsonSuccess([]);
        }
    }


    /**
     * 获取商品信息
     * @param string/array $id
     * @param int $state 状态-[0:全部,1:上架,2:下架]
     * @param int $act 活动信息获取-[1:获取,2:不获取]
     * * */
    public static function getGoodsInfo($id, $state = 0, $act = 1)
    {
        
        try {
            if (empty($id)) {
                throw new \Exception('参数异常');
            }
            if (!is_array($id)) {
                $id = [$id];
            }
            $where = ['and'];
            $where[] = ['in', 'id', $id];
            if (in_array($state, [1, 2])) {
                $where[] = ['=', 'state', $state];
            }
            $goods = GoodsModel::getAll($where,['id','barcode', 'name', 'thumb', 'sell', 'category', 'brand', 'mdl', 'state']);
            if (empty($goods)) {
                throw new \Exception('商品信息异常');
            }
            // 库存
            $stock = GoodsStockService::getStock($id);
            // 活动
            $activity = ActivePromotionService::getActivityInfo($id);

            // 优惠券
            // $cp = ActiveCouponService::getCouponByBarcode($goods);

            foreach ($goods as &$val) {
                $val['stock'] = isset($stock[$val['id']]) ? 1 : 2;
                $val['price'] = round($val['sell']); // 商品价格
                $val['activity_price'] = $val['price'];
                $val['act_tag'] = [];
                $val['act'] = [];
                // 匹配商品活动信息
                if ($activity && isset($activity[$val['id']])) {
                    $val['act'] = $activity[$val['id']];
                    $val['act_tag'][] = $activity[$val['id']]['tag'];
                    $val['activity_price'] = ActivePromotionService::getActivityPrice($activity[$val['id']], $val['price']);
                }
                $val['sell'] = $val['activity_price'] == $val['price'] ? "" : round($val['sell']);
                // if ($cp  && isset($cp[$val['id']])) {
                //     $val['cp'] = array_values($cp[$val['id']]);
                // }
                
                // $val['price'] = $val['activity_price'] == $val['price'] ? 0 : $val['price'];
            }
            return $goods;
        } catch (\Exception $exc) {
            return [];
        }
    }




    // 获取商品图文详情
    public static function getDesc($id)
    {
        try {
            $data = GoodsDescModel::getDataOne(['gid' => $id]);
            return self::jsonSuccess($data);
        } catch (\Exception $exc) {
            return self::jsonSuccess([]);
        }
    }


    // 获取商品浏览历史记录
    public static function history($params)
    {
        try {
            $headers = \Yii::$app->getRequest()->getHeaders();
            if(empty($headers->get('deviceId'))){
                throw new \Exception('商品异常');
            }
            $user_key = $headers->get('deviceId');
            
            $history_goods = GoodsLookModel::getDataAll(['user_key' => $user_key], $params['page']??1, 20, 'update_time desc', ['gid']);
            if (empty($history_goods['list'])) {
                return self::jsonSuccess([]);
            }
            $goods = GoodsService::getGoodsInfo(array_column($history_goods['list'], 'gid'), 1, 1);
            return self::jsonSuccess($goods);
        } catch (\Exception $exc) {
            return self::jsonSuccess();
        }
    }

    // 访问历史记录
    public static function addHistory($gid)
    {
        try {
            $headers = \Yii::$app->getRequest()->getHeaders();
            if(empty($headers->get('deviceId'))){
                throw new \Exception('商品异常');
            }
            $user_key = $headers->get('deviceId');
            $pdata = [
                'user_key' => $user_key,
                'gid'=>$gid,
                'update_time' => date('Y-m-d H:i:s')
            ];
            $cart = GoodsLookModel::findOne(['gid' => $gid, 'user_key' => $user_key]);
            if (empty($cart)) {
                GoodsLookModel::create($pdata);
                return self::jsonSuccess();
            }

            $cart->update_time = date('Y-m-d H:i:s');
            $cart->save();
            return self::jsonSuccess();
        } catch (\Exception $exc) {
            return self::jsonSuccess();
        }
    }
}
